import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Modal,
  Divider,
  Dropdown,
  Menu,
  Icon,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TableList from '@/components/TableList';
import {ruleP} from '@/utils/rule'
import styles from '../search.less';
const { TextArea } = Input;
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑短信模板':'新增短信模板'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="模板编码">
        {form.getFieldDecorator('code', {
          rules: [{required: true,message:'模板编码不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text&&text.code||''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem {...formLayout} label="模板名称">
        {form.getFieldDecorator('name', {
          rules: [{required: true,message:'模板名称不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text&&text.name||''
        })(
          <Input placeholder="请输入"/>
        )}
      </FormItem>
      <FormItem {...formLayout} label="模板内容">
        {form.getFieldDecorator('content', {
          rules: [{required: true,message:'模板内容不能为空'}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text&&text.content||''
        })(
          <Input placeholder="如:验证码为${code}…"/>
        )}
      </FormItem>
      <FormItem {...formLayout} label="备注">
      {form.getFieldDecorator('remark',{
        rules: [{max: 140, message: "字符长度不能超过140"}],
        initialValue: text&&text.remark||''})(
        <TextArea
          style={{minHeight: 32}}
          placeholder="请输入"
          rows={3}
        />)}
    </FormItem>
    </Modal>
  );
});

@Form.create()

/* eslint react/no-multi-comp:0 */
@connect(({messageTem, loading }) => ({
  messageTem,
  loading: loading.models.messageTem,
}))
@Form.create()
class MessageTem extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    text: {},
    uploading: false,
  };

  columns = [
    {
      title: '模板编码',
      dataIndex: 'code',
    },

    {
      title: '模板名称',
      dataIndex: 'name',
    },
    {
      title: '模板内容',
      dataIndex: 'content',
    },

    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true,record)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.handleModalVisible(true,record)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.pageList();//列表查询
  }

  // 分页查询列表
  pageList(res,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      code:res&& res.code,
      name: res&&res.name,
      type: 2,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'messageTem/queryList',
      payload: values,
      callback: (obj) => {
        if(obj.result == "ok" && res.userName) {

        }
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };
  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };
  handleThisRowDelete = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'messageTem/remove',
      payload: {id},
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            selectedRows: [],
          });
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      this.pageList(values);//列表查询
    });
  };


  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text,
    });
  };

  handleDetailModalVisible = (flag,text) => {
    this.setState({
      detailModalVisible: !!flag,
      text,
    });
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const params = {
      code: fields.code,
      name: fields.name,
      content: fields.content,
      remark: fields.remark,
      id: text.id,
    }
    dispatch({
      type: 'messageTem/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const params = {
      type: 2,
      code: fields.code,
      name: fields.name,
      content: fields.content,
      remark: fields.remark,
    }
    dispatch({
      type: 'messageTem/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };


  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="模板编码">
              {getFieldDecorator('code')(<Input placeholder=""/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="模板名称">
              {getFieldDecorator('name')(<Input placeholder=""/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      messageTem: { data },
      loading,
    } = this.props;

    const { selectedRows, modalVisible, updateModalVisible, editFormValues,detailModalVisible, text} = this.state;
    const parentMethods = {
      addDataFn: this.addDataFn,
      updateFn:this.updateFn,
      handleModalVisible: this.handleModalVisible,
    };
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };

    return (
    <PageHeaderWrapper title="短信内容模板">
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
        </div>
        {detailModalVisible?<Details {...detailsMethods} detailModalVisible={detailModalVisible} text={text} />:null}
      </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { detailModalVisible, handleDetailModalVisible, text} = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={12}>
            <FormItem {...formLayout} label="模板编码">
              {text.code}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="模板名称">
              {text.name}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="模板内容">
              {text.content}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="备注">
              {text.remark}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default MessageTem;
